package com.ydd.network.mina;

import android.content.Context;
import android.util.Log;

import com.ydd.model.event.MinaEvent;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * Created by tao on 17-3-23.
 */

public class ConnectionManager {
    private ConnectionConfig mConfig;
    private WeakReference<Context> mContext;
    private NioSocketConnector mConnector;
    private IoSession mSession;
    private InetSocketAddress mAddress;

    public ConnectionManager(ConnectionConfig config) {
        this.mConfig = config;
        this.mContext = new WeakReference<Context>(config.getContext());
        init();
    }


    private void init() {
        //添加过滤器
        mAddress = new InetSocketAddress(mConfig.getIp(), mConfig.getPort());
        mConnector = new NioSocketConnector();
        mConnector.getSessionConfig().setSendBufferSize(mConfig.getReadBUfferSize());
        mConnector.getFilterChain().addLast("logging", new LoggingFilter());
        mConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(
                new ObjectSerializationCodecFactory()));

        mConnector.setHandler(new DefaultHandler(mContext.get()));
    }

    public boolean connect() {
        try {
            ConnectFuture future = mConnector.connect(mAddress);
            future.awaitUninterruptibly();
            mSession = future.getSession();
        } catch (Exception e) {
            return false;
        }

        return mSession == null ? false : true;
    }

    public void disConnect() {
        mConnector.dispose();
        mConnector = null;
        mSession = null;
        mAddress = null;
        mContext = null;
    }

    private static class DefaultHandler extends IoHandlerAdapter {
        private Context mContext;

        public DefaultHandler(Context context) {
            this.mContext = context;
        }

        @Override
        public void sessionOpened(IoSession session) throws Exception {
            if (session != null) {
                SessionManager.getInstance().setSession(session);
            }
        }

        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            if (mContext != null) {
                EventBus.getDefault().post(new MinaEvent(message));
            }
        }

        @Override
        public void sessionClosed(IoSession session) throws Exception {
            SessionManager.getInstance().removeSession();
        }
    }
}
